package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.impl.client.HttpClients;
import org.apache.logging.log4j.LoggingException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {

    private final String WX_LOGIN = "https://api.weixin.qq.com/sns/jscode2session";

    @Autowired
    private WeChatProperties weChatProperties;
    @Autowired
    private UserMapper userMapper;
    @Override
    public User weChatLogin(UserLoginDTO userLoginDTO) {
//        调用微信接口服务，获得当前微信用户的openId
//        构建参数列表
        Map<String, String> param = new HashMap<>();
        param.put("appid",weChatProperties.getAppid());
        param.put("secret",weChatProperties.getSecret());
        param.put("js_code",userLoginDTO.getCode());
        param.put("grant_type","authorization_code");
//        发送请求，param为参数列表
        String s = HttpClientUtil.doGet(WX_LOGIN,param);
        JSONObject jsonObject = JSON.parseObject(s);
        String open_id = jsonObject.getString("openid");
//        判断openId是否为空，如果是空则代表登录失败，抛出业务异常
        if (open_id == null){
            throw new LoggingException(MessageConstant.LOGIN_FAILED);
        }
//        判断是否为新用户
        User user = userMapper.selectUserByOpenId(open_id);
        if (user == null){
            user = User.builder()
                    .openid(open_id)
                    .createTime(LocalDateTime.now())
                    .build();
            userMapper.insertUser(user);
        }
//        返回
        return user;
    }
}
